/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2025 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "i2c.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <string.h>
#include <stdlib.h>
#include "oled.h"
#include "dht11.h"
#include "stepmotor.h"
#include "wifi.h"
#include "ali_yun.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
#define Light_Command 0x10
#define Fin_Command 0x20
#define Humi_Command 0x30
#define Wash_Command 0x40
#define curtain_Command 0x50

#define On_Command 0x11
#define Off_Command 0x00
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void delay_init(uint8_t SYSCLK);
void is_serial_interrupt(void);
void dataDisplay(void);
void get_lighting_PPH_values(void);
void buzzer_warning(void);
void motor_control(void);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

uint8_t USART1_RxBuff[128];
volatile uint8_t USART1_RxCounter;
#if 1
// wifi
uint8_t wifi_RxBuff[256];
volatile uint8_t wifi_RxCounter;
#endif
uint32_t fac_us = 0; // us延时倍乘数
uint8_t humiH, humiL, tempH, tempL;
uint8_t light, pph;
enum
{
    staticState = 0,
    ON,
    OFF,
} motor_state = staticState;
uint8_t voice_buf[4] = {0};
uint8_t buf[8] = {0xAA, 0x55, 0x01, 0x00, 0x00, 0x55, 0xAA, 0x00};
static char data[] = "h 0  s 0  b 0  f 0  l 0  tem 27  hum 32";

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  MX_USART3_UART_Init();
  MX_I2C1_Init();
  MX_ADC1_Init();
  /* USER CODE BEGIN 2 */

    delay_init(72);

    FS_DHT11_Init();

    HAL_Delay(100);
    OLED_Init();
    OLED_Clear();
    OLED_Display_On();
    // 等待 语言模块/网络模块 启动
    HAL_Delay(1000);
    HAL_UART_Receive_IT(&huart1, USART1_RxBuff, sizeof(USART1_RxBuff));
    __HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);
#if 1
    HAL_UART_Receive_IT(&huart3, wifi_RxBuff, sizeof(wifi_RxBuff));
    __HAL_UART_ENABLE_IT(&huart3, UART_IT_IDLE);
#endif
    HAL_Delay(100);
    uint16_t count = 0;

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
    initialDisplay();
    WIFI_Connect();
    Mosquitto_Init();
    u1_USART("\n测试发布结束 \n");
    while (1)
    {

        HAL_UART_Receive_IT(&huart2, voice_buf, 4);
        is_serial_interrupt();

        HAL_Delay(1);
        if (count++ == 1000)
        {
            count = 0;
            static uint32_t time = 0;
            //get_lighting_PPH_values();
            DHT11_Read_Data(&humiH, &humiL, &tempH, &tempL);
            buzzer_warning();
            motor_control();
            dataDisplay();
            //// hum_status 0  shower_status 0  buzzer 0  fan 0  led 0  tem 27  hum 32
            //"h 0  s 0  b 0  f 0  l 0  tem 27  hum 32"
            data[2] = HAL_GPIO_ReadPin(HUMIDIFICATION_GPIO_Port, HUMIDIFICATION_Pin) ? '1' : '0';
            data[7] = HAL_GPIO_ReadPin(WASH_GPIO_Port, WASH_Pin) ? '1' : '0';      // shower_status
            data[12] = HAL_GPIO_ReadPin(BUZZER_GPIO_Port, BUZZER_Pin) ? '1' : '0'; // buzzer
            data[17] = HAL_GPIO_ReadPin(FIN_GPIO_Port, FIN_Pin) ? '1' : '0';       // fan
            data[22] = HAL_GPIO_ReadPin(LED4_GPIO_Port, LED4_Pin) ? '1' : '0';     // led
            Publish(data);
            sprintf(&data[25], "tem %d  hum %d", tempH, humiH);

            u1_USART("time %d\n", time = (time + 1) & 0xFFFF);
        }
    }

    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */

  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
  PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV6;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart == &huart2)
    {
        if (voice_buf[0] == 0x11 && voice_buf[1] == 0x11 && voice_buf[2] == 0x11 && voice_buf[3] == 0x11)
        {
            buf[3] = humiH;
            buf[4] = tempH;
            HAL_UART_Transmit_IT(&huart2, buf, 8);
            return;
        }
        else if (voice_buf[0] == 0x00 && voice_buf[1] == 0x00)
            switch (voice_buf[2])
            {
            case Light_Command:
                HAL_GPIO_WritePin(LED4_GPIO_Port, LED4_Pin, (voice_buf[3] == On_Command) ? GPIO_PIN_SET : GPIO_PIN_RESET);
                break;
            case Fin_Command:
                HAL_GPIO_WritePin(FIN_GPIO_Port, FIN_Pin, (voice_buf[3] == On_Command) ? GPIO_PIN_SET : GPIO_PIN_RESET);
                break;
            case Humi_Command:
                HAL_GPIO_WritePin(HUMIDIFICATION_GPIO_Port, HUMIDIFICATION_Pin, (voice_buf[3] == On_Command) ? GPIO_PIN_SET : GPIO_PIN_RESET);
                break;
            case Wash_Command:
                HAL_GPIO_WritePin(WASH_GPIO_Port, WASH_Pin, (voice_buf[3] == On_Command) ? GPIO_PIN_SET : GPIO_PIN_RESET);
                break;
            case curtain_Command:
                if (voice_buf[3] == On_Command || voice_buf[3] == Off_Command)
                    motor_state = ((voice_buf[3] == On_Command) ? ON : OFF);
                break;
            default:
                break;
            }
    }
}

void delay_init(uint8_t SYSCLK)
{
    fac_us = SYSCLK;
}
void dataDisplay()
{
    OLED_ShowNum(30, 0, humiH, 2, 12);
    OLED_ShowNum(100, 0, tempH, 2, 12);
    OLED_ShowString(36, 2, HAL_GPIO_ReadPin(LED4_GPIO_Port, LED4_Pin) ? (uint8_t *)"ON " : (uint8_t *)"OFF", 12);
    OLED_ShowString(100, 2, HAL_GPIO_ReadPin(FIN_GPIO_Port, FIN_Pin) ? (uint8_t *)"ON " : (uint8_t *)"OFF", 12);
    OLED_ShowString(32, 4, HAL_GPIO_ReadPin(HUMIDIFICATION_GPIO_Port, HUMIDIFICATION_Pin) ? (uint8_t *)"ON " : (uint8_t *)"OFF", 12);
    OLED_ShowString(100, 4, HAL_GPIO_ReadPin(WASH_GPIO_Port, WASH_Pin) ? (uint8_t *)"ON " : (uint8_t *)"OFF", 12);
    OLED_ShowNum(16, 6, light, 2, 12);
    OLED_ShowNum(80, 6, pph, 2, 12);
    // OLED_ShowString(44, 7, 1 ? (uint8_t*)"auto" : (uint8_t*)"manual", 12);
}
void get_lighting_PPH_values()
{
    HAL_ADC_Start(&hadc1);
    HAL_ADC_PollForConversion(&hadc1, 100);
    uint32_t ADC_LIGHT = HAL_ADC_GetValue(&hadc1);

    HAL_ADC_Start(&hadc1);
    HAL_ADC_PollForConversion(&hadc1, 100);
    uint32_t ADC_PPH = HAL_ADC_GetValue(&hadc1);
    light = (float)(ADC_LIGHT) / 4095 * 100;
    pph = (float)(ADC_PPH) / 4095 * 100;
}
void is_serial_interrupt()
{
    if (USART1_RxCounter)
    {
        switch (USART1_RxBuff[0])
        {
            // hum_status 0  shower_status 0  buzzer 0  fan 0  led 0
        case 'l':
            HAL_GPIO_WritePin(LED4_GPIO_Port, LED4_Pin, (USART1_RxBuff[2] == '1') ? GPIO_PIN_SET : GPIO_PIN_RESET);
            break;
        case 'f':
            HAL_GPIO_WritePin(FIN_GPIO_Port, FIN_Pin, (USART1_RxBuff[2] == '1') ? GPIO_PIN_SET : GPIO_PIN_RESET);
            break;
        case 'b':
            HAL_GPIO_WritePin(BUZZER_GPIO_Port, BUZZER_Pin, (USART1_RxBuff[2] == '1') ? GPIO_PIN_SET : GPIO_PIN_RESET);
            break;
        case 'h':
            HAL_GPIO_WritePin(HUMIDIFICATION_GPIO_Port, HUMIDIFICATION_Pin, (USART1_RxBuff[2] == '1') ? GPIO_PIN_SET : GPIO_PIN_RESET);
            break;
        case 's':
            HAL_GPIO_WritePin(WASH_GPIO_Port, WASH_Pin, (USART1_RxBuff[2] == '1') ? GPIO_PIN_SET : GPIO_PIN_RESET);
            break;
        default:
            break;
        }
        USART1_RxCounter = 0;
        memset(USART1_RxBuff, 0, sizeof(USART1_RxBuff));
        dataDisplay();
    }
#if 1
    else if (wifi_RxCounter)
    {
        u1_USART("--------------------\n");
        HAL_UART_Transmit(&huart1, wifi_RxBuff, sizeof(wifi_RxBuff), 1000);
        u1_USART("--------------------\n");
        //+MQTTSUBRECV:0,"set",3,h 1
        if (strncmp((char *)wifi_RxBuff, "AT", 2) == 0)
        {
        }
        else if (strncmp((char *)wifi_RxBuff, "+MQTTSUBRECV:0,\"set\",", 19) == 0)
        {
            u1_USART("++++++++++++++++++++\n");
            char *strPtr = (char *)wifi_RxBuff + 23;
            u1_USART(strPtr);
            switch (strPtr[0])
            {
                // hum_status 0  shower_status 0  buzzer 0  fan 0  led 0
            case 'l':
                HAL_GPIO_WritePin(LED4_GPIO_Port, LED4_Pin, (strPtr[2] == '1') ? GPIO_PIN_SET : GPIO_PIN_RESET);
                break;
            case 'f':
                HAL_GPIO_WritePin(FIN_GPIO_Port, FIN_Pin, (strPtr[2] == '1') ? GPIO_PIN_SET : GPIO_PIN_RESET);
                break;
            case 'b':
                HAL_GPIO_WritePin(BUZZER_GPIO_Port, BUZZER_Pin, (strPtr[2] == '1') ? GPIO_PIN_SET : GPIO_PIN_RESET);
                break;
            case 'h':
                HAL_GPIO_WritePin(HUMIDIFICATION_GPIO_Port, HUMIDIFICATION_Pin, (strPtr[2] == '1') ? GPIO_PIN_SET : GPIO_PIN_RESET);
                break;
            case 's':
                HAL_GPIO_WritePin(WASH_GPIO_Port, WASH_Pin, (strPtr[2] == '1') ? GPIO_PIN_SET : GPIO_PIN_RESET);
                break;
            default:
                break;
            }
        }
        wifi_RxCounter = 0;
        memset(wifi_RxBuff, 0, sizeof(wifi_RxBuff));
    }
    else
    {
        return;
    }
#endif
}
void buzzer_warning()
{
    HAL_GPIO_WritePin(BUZZER_GPIO_Port, BUZZER_Pin, pph > 80 ? GPIO_PIN_SET : GPIO_PIN_RESET);
}

void motor_control()
{
    if (motor_state != staticState)
    {
        MOTOR_Direction_Angle((motor_state == ON ? 1 : 0), 0, 180, 1);
        motor_state = staticState;
        HAL_GPIO_WritePin(GPIOB, ELECTRIC_2_Pin | ELECTRIC_3_Pin | ELECTRIC_3_Pin, GPIO_PIN_RESET);
        HAL_GPIO_WritePin(GPIOA, ELECTRIC_1_Pin, GPIO_PIN_RESET);
    }
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */
    __disable_irq();
    while (1)
    {
    }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
    /* User can add his own implementation to report the file name and line number,
       ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
